<template>
  <div class="login-page">
    <div class="container">
      <h2>用户登录</h2>
      <el-form :model="loginForm" ref="loginForm" :rules="rules">
        <el-form-item prop="email">
          <el-input 
            v-model="loginForm.email" 
            placeholder="请输入邮箱"
            prefix-icon="Message"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loading">
          登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../store/authStore';

const router = useRouter();
const authStore = useAuthStore();
const loading = ref(false);

const loginForm = reactive({
  email: '',
  password: ''
});

const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  loading.value = true;
  try {
    const response = await fetch('https://penglink.pcwxcn.top/api/user/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: loginForm.email,
        password: loginForm.password
      })
    });

    const data = await response.json();
    if (data.code === 200) {
      ElMessage.success('登录成功');
      
      // 获取用户信息和权限
      try {
        const userInfoResponse = await fetch('https://penglink.pcwxcn.top/api/user/info', {
          headers: {
            'Authorization': `Bearer ${data.data.token}`,
            'Accept': 'application/json'
          }
        });
        
        if (!userInfoResponse.ok) {
          throw new Error('获取用户信息失败');
        }
        
        const userInfoData = await userInfoResponse.json();
        if (userInfoData.code === 200) {
          // 保存用户信息、角色和设备权限
          const userInfo = userInfoData.data;
          const userRole = userInfo.role || 'LV4'; // 默认为普通用户
          
          // 处理设备权限数据
          let devicesList = [];
          if (userInfo.devices) {
            if (Array.isArray(userInfo.devices)) {
              devicesList = userInfo.devices;
            } else if (typeof userInfo.devices === 'string') {
              // 尝试解析字符串形式的devices
              try {
                devicesList = JSON.parse(userInfo.devices);
                if (!Array.isArray(devicesList)) {
                  devicesList = [devicesList]; // 如果解析后不是数组，则转为数组
                }
              } catch (e) {
                // 如果解析失败，尝试将其作为单个设备ID处理
                devicesList = [userInfo.devices];
  
              }
            } else {
              // 如果是其他类型，尝试转换为数组
              devicesList = [userInfo.devices];
            }
          }
          

          
          // 保存登录状态和用户信息
          authStore.login({
            token: data.data.token,
            role: userRole,
            userInfo: {
              ...userInfo,
              // 确保devices字段是数组
              devices: devicesList
            }
          });
          
          
          router.push('/dashboard');
        } else {
          throw new Error(userInfoData.msg || '获取用户信息失败');
        }
      } catch (error) {
        // 如果获取用户信息失败，仍然保存token并跳转
        console.error('获取用户信息失败:', error);
        authStore.setToken(data.data.token);
        router.push('/dashboard');
      }
    } else {
      ElMessage.error(data.msg || '登录失败，请检查账号密码');
    }
  } catch (error) {
    ElMessage.error('登录失败：' + error.message);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 样式保持不变 */
</style>